package com.cencat.driver.service.impl;

import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.cencat.common.utils.RedisUtils;
import com.cencat.driver.entity.DeliveryTask;
import com.cencat.driver.mapper.DeliveryTaskMapper;
import com.cencat.driver.service.DeliveryTaskService;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDateTime;
import java.util.*;
import java.util.concurrent.TimeUnit;

/**
 * 配送任务服务实现类
 * 
 * @author cencat
 * @since 2024-01-01
 */
@Slf4j
@Service
@RequiredArgsConstructor
public class DeliveryTaskServiceImpl extends ServiceImpl<DeliveryTaskMapper, DeliveryTask> implements DeliveryTaskService {

    private final DeliveryTaskMapper deliveryTaskMapper;
    private final RedisUtils redisUtils;

    private static final String TASK_CODE_PREFIX = "TASK";
    private static final String TASK_LOCK_PREFIX = "task:lock:";
    private static final String TASK_TIMEOUT_KEY = "task:timeout:";

    @Override
    public DeliveryTask getByTaskCode(String taskCode, Long tenantId) {
        return deliveryTaskMapper.selectByTaskCode(taskCode, tenantId);
    }

    @Override
    public List<DeliveryTask> getByDriverId(Long driverId, Long tenantId) {
        return deliveryTaskMapper.selectByDriverId(driverId, tenantId);
    }

    @Override
    public List<DeliveryTask> getByOrderId(Long orderId, Long tenantId) {
        return deliveryTaskMapper.selectByOrderId(orderId, tenantId);
    }

    @Override
    public List<DeliveryTask> getByStatus(Integer status, Long tenantId) {
        return deliveryTaskMapper.selectByStatus(status, tenantId);
    }

    @Override
    public List<DeliveryTask> getPendingTasksByDriverId(Long driverId, Long tenantId) {
        return deliveryTaskMapper.selectPendingTasksByDriverId(driverId, tenantId);
    }

    @Override
    public List<DeliveryTask> getUnassignedTasks(Long tenantId) {
        return deliveryTaskMapper.selectUnassignedTasks(tenantId);
    }

    @Override
    public IPage<DeliveryTask> getPageList(Long current, Long size, String taskCode, Long driverId, Long orderId,
                                         Integer status, Integer priority, LocalDateTime startTime, LocalDateTime endTime, Long tenantId) {
        Page<DeliveryTask> page = new Page<>(current, size);
        return deliveryTaskMapper.selectPageList(page, taskCode, driverId, orderId, status, priority, startTime, endTime, tenantId);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean createTask(DeliveryTask deliveryTask) {
        try {
            // 生成任务编号
            deliveryTask.setTaskCode(generateTaskCode(deliveryTask.getTenantId()));
            
            // 设置默认值
            deliveryTask.setStatus(DeliveryTask.Status.PENDING.getValue());
            deliveryTask.setCreateTime(LocalDateTime.now());
            deliveryTask.setUpdateTime(LocalDateTime.now());
            
            int result = deliveryTaskMapper.insert(deliveryTask);
            
            log.info("创建配送任务成功: taskId={}, taskCode={}, orderId={}, tenantId={}", 
                    deliveryTask.getId(), deliveryTask.getTaskCode(), deliveryTask.getOrderId(), deliveryTask.getTenantId());
            
            return result > 0;
            
        } catch (Exception e) {
            log.error("创建配送任务异常: orderId={}, tenantId={}", deliveryTask.getOrderId(), deliveryTask.getTenantId(), e);
            throw new RuntimeException("创建配送任务失败", e);
        }
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean updateTask(DeliveryTask deliveryTask) {
        try {
            DeliveryTask existTask = deliveryTaskMapper.selectById(deliveryTask.getId());
            if (existTask == null || !deliveryTask.getTenantId().equals(existTask.getTenantId())) {
                return false;
            }
            
            deliveryTask.setUpdateTime(LocalDateTime.now());
            
            int result = deliveryTaskMapper.updateById(deliveryTask);
            
            log.info("更新配送任务成功: taskId={}, taskCode={}, tenantId={}", 
                    deliveryTask.getId(), deliveryTask.getTaskCode(), deliveryTask.getTenantId());
            
            return result > 0;
            
        } catch (Exception e) {
            log.error("更新配送任务异常: taskId={}, tenantId={}", deliveryTask.getId(), deliveryTask.getTenantId(), e);
            throw new RuntimeException("更新配送任务失败", e);
        }
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean deleteTask(Long id, Long tenantId) {
        try {
            DeliveryTask task = deliveryTaskMapper.selectById(id);
            if (task == null || !tenantId.equals(task.getTenantId())) {
                return false;
            }
            
            // 检查任务状态，只有待分配和已取消的任务可以删除
            if (!DeliveryTask.Status.PENDING.getValue().equals(task.getStatus()) && 
                !DeliveryTask.Status.CANCELLED.getValue().equals(task.getStatus())) {
                throw new RuntimeException("任务状态不允许删除");
            }
            
            int result = deliveryTaskMapper.deleteById(id);
            
            log.info("删除配送任务成功: taskId={}, taskCode={}, tenantId={}", 
                    id, task.getTaskCode(), tenantId);
            
            return result > 0;
            
        } catch (Exception e) {
            log.error("删除配送任务异常: taskId={}, tenantId={}", id, tenantId, e);
            throw new RuntimeException("删除配送任务失败", e);
        }
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean batchDeleteTasks(List<Long> ids, Long tenantId) {
        try {
            for (Long id : ids) {
                if (!deleteTask(id, tenantId)) {
                    throw new RuntimeException("批量删除配送任务失败: taskId=" + id);
                }
            }
            return true;
        } catch (Exception e) {
            log.error("批量删除配送任务异常: tenantId={}", tenantId, e);
            throw new RuntimeException("批量删除配送任务失败", e);
        }
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean assignToDriver(Long id, Long driverId, Long tenantId) {
        String lockKey = TASK_LOCK_PREFIX + id;
        
        try {
            // 使用Redis分布式锁防止并发分配
            if (!redisUtils.setIfAbsent(lockKey, "1", 30, TimeUnit.SECONDS)) {
                throw new RuntimeException("任务正在被处理，请稍后重试");
            }
            
            DeliveryTask task = deliveryTaskMapper.selectById(id);
            if (task == null || !tenantId.equals(task.getTenantId())) {
                return false;
            }
            
            // 检查任务状态
            if (!DeliveryTask.Status.PENDING.getValue().equals(task.getStatus())) {
                throw new RuntimeException("任务状态不允许分配");
            }
            
            // 检查任务是否已分配
            if (task.getDriverId() != null) {
                throw new RuntimeException("任务已分配给其他司机");
            }
            
            int result = deliveryTaskMapper.assignToDriver(id, driverId, tenantId);
            
            log.info("任务分配司机成功: taskId={}, driverId={}, tenantId={}", id, driverId, tenantId);
            
            return result > 0;
            
        } catch (Exception e) {
            log.error("任务分配司机异常: taskId={}, driverId={}, tenantId={}", id, driverId, tenantId, e);
            throw new RuntimeException("任务分配司机失败", e);
        } finally {
            redisUtils.delete(lockKey);
        }
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean batchAssignToDriver(List<Long> taskIds, Long driverId, Long tenantId) {
        try {
            for (Long taskId : taskIds) {
                if (!assignToDriver(taskId, driverId, tenantId)) {
                    throw new RuntimeException("批量分配任务失败: taskId=" + taskId);
                }
            }
            return true;
        } catch (Exception e) {
            log.error("批量分配任务异常: driverId={}, tenantId={}", driverId, tenantId, e);
            throw new RuntimeException("批量分配任务失败", e);
        }
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean acceptTask(Long id, Long driverId, Long tenantId) {
        String lockKey = TASK_LOCK_PREFIX + id;
        
        try {
            if (!redisUtils.setIfAbsent(lockKey, "1", 30, TimeUnit.SECONDS)) {
                throw new RuntimeException("任务正在被处理，请稍后重试");
            }
            
            DeliveryTask task = deliveryTaskMapper.selectById(id);
            if (task == null || !tenantId.equals(task.getTenantId())) {
                return false;
            }
            
            // 检查任务状态和司机
            if (!DeliveryTask.Status.ASSIGNED.getValue().equals(task.getStatus()) || 
                !driverId.equals(task.getDriverId())) {
                throw new RuntimeException("任务状态异常或司机不匹配");
            }
            
            int result = deliveryTaskMapper.updateStatus(id, DeliveryTask.Status.ACCEPTED.getValue(), tenantId);
            
            log.info("司机接受任务成功: taskId={}, driverId={}, tenantId={}", id, driverId, tenantId);
            
            return result > 0;
            
        } catch (Exception e) {
            log.error("司机接受任务异常: taskId={}, driverId={}, tenantId={}", id, driverId, tenantId, e);
            throw new RuntimeException("司机接受任务失败", e);
        } finally {
            redisUtils.delete(lockKey);
        }
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean rejectTask(Long id, Long driverId, String rejectReason, Long tenantId) {
        String lockKey = TASK_LOCK_PREFIX + id;
        
        try {
            if (!redisUtils.setIfAbsent(lockKey, "1", 30, TimeUnit.SECONDS)) {
                throw new RuntimeException("任务正在被处理，请稍后重试");
            }
            
            DeliveryTask task = deliveryTaskMapper.selectById(id);
            if (task == null || !tenantId.equals(task.getTenantId())) {
                return false;
            }
            
            // 检查任务状态和司机
            if (!DeliveryTask.Status.ASSIGNED.getValue().equals(task.getStatus()) || 
                !driverId.equals(task.getDriverId())) {
                throw new RuntimeException("任务状态异常或司机不匹配");
            }
            
            // 更新任务状态为待分配，清除司机分配
            task.setStatus(DeliveryTask.Status.PENDING.getValue());
            task.setDriverId(null);
            task.setRejectReason(rejectReason);
            task.setUpdateTime(LocalDateTime.now());
            
            int result = deliveryTaskMapper.updateById(task);
            
            log.info("司机拒绝任务成功: taskId={}, driverId={}, reason={}, tenantId={}", 
                    id, driverId, rejectReason, tenantId);
            
            return result > 0;
            
        } catch (Exception e) {
            log.error("司机拒绝任务异常: taskId={}, driverId={}, tenantId={}", id, driverId, tenantId, e);
            throw new RuntimeException("司机拒绝任务失败", e);
        } finally {
            redisUtils.delete(lockKey);
        }
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean startDelivery(Long id, Long driverId, Long tenantId) {
        try {
            DeliveryTask task = deliveryTaskMapper.selectById(id);
            if (task == null || !tenantId.equals(task.getTenantId())) {
                return false;
            }
            
            // 检查任务状态和司机
            if (!DeliveryTask.Status.ACCEPTED.getValue().equals(task.getStatus()) || 
                !driverId.equals(task.getDriverId())) {
                throw new RuntimeException("任务状态异常或司机不匹配");
            }
            
            task.setStatus(DeliveryTask.Status.IN_PROGRESS.getValue());
            task.setStartTime(LocalDateTime.now());
            task.setUpdateTime(LocalDateTime.now());
            
            int result = deliveryTaskMapper.updateById(task);
            
            log.info("开始配送成功: taskId={}, driverId={}, tenantId={}", id, driverId, tenantId);
            
            return result > 0;
            
        } catch (Exception e) {
            log.error("开始配送异常: taskId={}, driverId={}, tenantId={}", id, driverId, tenantId, e);
            throw new RuntimeException("开始配送失败", e);
        }
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean completeDelivery(Long id, Long driverId, Long tenantId) {
        try {
            DeliveryTask task = deliveryTaskMapper.selectById(id);
            if (task == null || !tenantId.equals(task.getTenantId())) {
                return false;
            }
            
            // 检查任务状态和司机
            if (!DeliveryTask.Status.IN_PROGRESS.getValue().equals(task.getStatus()) || 
                !driverId.equals(task.getDriverId())) {
                throw new RuntimeException("任务状态异常或司机不匹配");
            }
            
            task.setStatus(DeliveryTask.Status.COMPLETED.getValue());
            task.setCompleteTime(LocalDateTime.now());
            task.setUpdateTime(LocalDateTime.now());
            
            int result = deliveryTaskMapper.updateById(task);
            
            log.info("完成配送成功: taskId={}, driverId={}, tenantId={}", id, driverId, tenantId);
            
            return result > 0;
            
        } catch (Exception e) {
            log.error("完成配送异常: taskId={}, driverId={}, tenantId={}", id, driverId, tenantId, e);
            throw new RuntimeException("完成配送失败", e);
        }
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean updateStatus(Long id, Integer status, Long tenantId) {
        try {
            DeliveryTask task = deliveryTaskMapper.selectById(id);
            if (task == null || !tenantId.equals(task.getTenantId())) {
                return false;
            }
            
            int result = deliveryTaskMapper.updateStatus(id, status, tenantId);
            
            log.info("更新任务状态成功: taskId={}, status={}, tenantId={}", id, status, tenantId);
            
            return result > 0;
            
        } catch (Exception e) {
            log.error("更新任务状态异常: taskId={}, status={}, tenantId={}", id, status, tenantId, e);
            throw new RuntimeException("更新任务状态失败", e);
        }
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean batchUpdateStatus(List<Long> ids, Integer status, Long tenantId) {
        try {
            for (Long id : ids) {
                if (!updateStatus(id, status, tenantId)) {
                    throw new RuntimeException("批量更新任务状态失败: taskId=" + id);
                }
            }
            return true;
        } catch (Exception e) {
            log.error("批量更新任务状态异常: tenantId={}", tenantId, e);
            throw new RuntimeException("批量更新任务状态失败", e);
        }
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean updateLocation(Long id, Double longitude, Double latitude, String address, Long tenantId) {
        try {
            int result = deliveryTaskMapper.updateLocation(id, longitude, latitude, address, tenantId);
            
            log.debug("更新任务位置成功: taskId={}, longitude={}, latitude={}, tenantId={}", 
                     id, longitude, latitude, tenantId);
            
            return result > 0;
            
        } catch (Exception e) {
            log.error("更新任务位置异常: taskId={}, tenantId={}", id, tenantId, e);
            return false;
        }
    }

    @Override
    public String generateTaskCode(Long tenantId) {
        String datePart = LocalDateTime.now().format(java.time.format.DateTimeFormatter.ofPattern("yyyyMMdd"));
        String randomPart = String.format("%06d", new Random().nextInt(1000000));
        return TASK_CODE_PREFIX + datePart + randomPart;
    }

    @Override
    public boolean validateTaskCodeUniqueness(String taskCode, Long excludeId, Long tenantId) {
        DeliveryTask existTask = deliveryTaskMapper.selectByTaskCode(taskCode, tenantId);
        return existTask == null || (excludeId != null && excludeId.equals(existTask.getId()));
    }

    @Override
    public List<DeliveryTask> getTimeoutTasks(Integer timeoutMinutes, Long tenantId) {
        return deliveryTaskMapper.selectTimeoutTasks(timeoutMinutes, tenantId);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public Map<String, Object> handleTimeoutTasks(Long tenantId) {
        Map<String, Object> result = new HashMap<>();
        int handledCount = 0;
        
        try {
            // 获取超时任务（30分钟未处理）
            List<DeliveryTask> timeoutTasks = getTimeoutTasks(30, tenantId);
            
            for (DeliveryTask task : timeoutTasks) {
                // 根据任务状态进行不同处理
                if (DeliveryTask.Status.ASSIGNED.getValue().equals(task.getStatus())) {
                    // 已分配但未接受的任务，重新分配
                    task.setStatus(DeliveryTask.Status.PENDING.getValue());
                    task.setDriverId(null);
                    task.setUpdateTime(LocalDateTime.now());
                    deliveryTaskMapper.updateById(task);
                    handledCount++;
                }
            }
            
            result.put("success", true);
            result.put("handledCount", handledCount);
            result.put("message", "处理超时任务完成");
            
            log.info("处理超时任务完成: 处理{}个任务, tenantId={}", handledCount, tenantId);
            
        } catch (Exception e) {
            log.error("处理超时任务异常: tenantId={}", tenantId, e);
            result.put("success", false);
            result.put("message", "处理超时任务失败: " + e.getMessage());
        }
        
        return result;
    }

    @Override
    public Map<String, Object> intelligentDispatch(Long taskId, Long tenantId) {
        Map<String, Object> result = new HashMap<>();
        
        try {
            DeliveryTask task = deliveryTaskMapper.selectById(taskId);
            if (task == null || !tenantId.equals(task.getTenantId())) {
                result.put("success", false);
                result.put("message", "任务不存在");
                return result;
            }
            
            // 智能派单逻辑：根据距离、工作负载、司机评分等因素选择最优司机
            List<Map<String, Object>> availableDrivers = deliveryTaskMapper.selectAvailableDriversForTask(taskId, tenantId);
            
            if (availableDrivers.isEmpty()) {
                result.put("success", false);
                result.put("message", "暂无可用司机");
                return result;
            }
            
            // 选择最优司机（这里简化为选择第一个）
            Map<String, Object> bestDriver = availableDrivers.get(0);
            Long driverId = Long.valueOf(bestDriver.get("id").toString());
            
            if (assignToDriver(taskId, driverId, tenantId)) {
                result.put("success", true);
                result.put("message", "智能派单成功");
                result.put("driverId", driverId);
                result.put("driverName", bestDriver.get("name"));
            } else {
                result.put("success", false);
                result.put("message", "派单失败");
            }
            
        } catch (Exception e) {
            log.error("智能派单异常: taskId={}, tenantId={}", taskId, tenantId, e);
            result.put("success", false);
            result.put("message", "智能派单失败: " + e.getMessage());
        }
        
        return result;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public Map<String, Object> batchIntelligentDispatch(List<Long> taskIds, Long tenantId) {
        Map<String, Object> result = new HashMap<>();
        int successCount = 0;
        int failCount = 0;
        
        try {
            for (Long taskId : taskIds) {
                Map<String, Object> dispatchResult = intelligentDispatch(taskId, tenantId);
                if (Boolean.TRUE.equals(dispatchResult.get("success"))) {
                    successCount++;
                } else {
                    failCount++;
                }
            }
            
            result.put("success", true);
            result.put("successCount", successCount);
            result.put("failCount", failCount);
            result.put("message", "批量智能派单完成");
            
        } catch (Exception e) {
            log.error("批量智能派单异常: tenantId={}", tenantId, e);
            result.put("success", false);
            result.put("message", "批量智能派单失败: " + e.getMessage());
        }
        
        return result;
    }

    @Override
    public Map<String, Object> getStatistics(Long tenantId) {
        Map<String, Object> statistics = new HashMap<>();
        
        try {
            Long totalCount = deliveryTaskMapper.countByTenantId(tenantId);
            Long pendingCount = deliveryTaskMapper.countByStatus(DeliveryTask.Status.PENDING.getValue(), tenantId);
            Long assignedCount = deliveryTaskMapper.countByStatus(DeliveryTask.Status.ASSIGNED.getValue(), tenantId);
            Long acceptedCount = deliveryTaskMapper.countByStatus(DeliveryTask.Status.ACCEPTED.getValue(), tenantId);
            Long inProgressCount = deliveryTaskMapper.countByStatus(DeliveryTask.Status.IN_PROGRESS.getValue(), tenantId);
            Long completedCount = deliveryTaskMapper.countByStatus(DeliveryTask.Status.COMPLETED.getValue(), tenantId);
            Long cancelledCount = deliveryTaskMapper.countByStatus(DeliveryTask.Status.CANCELLED.getValue(), tenantId);
            
            statistics.put("totalCount", totalCount);
            statistics.put("pendingCount", pendingCount);
            statistics.put("assignedCount", assignedCount);
            statistics.put("acceptedCount", acceptedCount);
            statistics.put("inProgressCount", inProgressCount);
            statistics.put("completedCount", completedCount);
            statistics.put("cancelledCount", cancelledCount);
            
            // 计算完成率
            double completionRate = totalCount > 0 ? (double) completedCount / totalCount * 100 : 0;
            statistics.put("completionRate", completionRate);
            
        } catch (Exception e) {
            log.error("获取任务统计信息异常: tenantId={}", tenantId, e);
        }
        
        return statistics;
    }

    @Override
    public Map<String, Object> getDriverTaskStatistics(Long driverId, Long tenantId) {
        Map<String, Object> statistics = new HashMap<>();
        
        try {
            Long totalCount = deliveryTaskMapper.countByDriverId(driverId, tenantId);
            Long completedCount = deliveryTaskMapper.countByDriverIdAndStatus(driverId, DeliveryTask.Status.COMPLETED.getValue(), tenantId);
            Long inProgressCount = deliveryTaskMapper.countByDriverIdAndStatus(driverId, DeliveryTask.Status.IN_PROGRESS.getValue(), tenantId);
            Long pendingCount = deliveryTaskMapper.countByDriverIdAndStatus(driverId, DeliveryTask.Status.ACCEPTED.getValue(), tenantId);
            
            statistics.put("totalCount", totalCount);
            statistics.put("completedCount", completedCount);
            statistics.put("inProgressCount", inProgressCount);
            statistics.put("pendingCount", pendingCount);
            
            // 计算完成率
            double completionRate = totalCount > 0 ? (double) completedCount / totalCount * 100 : 0;
            statistics.put("completionRate", completionRate);
            
        } catch (Exception e) {
            log.error("获取司机任务统计信息异常: driverId={}, tenantId={}", driverId, tenantId, e);
        }
        
        return statistics;
    }

    @Override
    public Map<String, Object> getTodayStatistics(Long driverId, Long tenantId) {
        Map<String, Object> statistics = new HashMap<>();
        
        try {
            LocalDateTime startOfDay = LocalDateTime.now().withHour(0).withMinute(0).withSecond(0).withNano(0);
            LocalDateTime endOfDay = startOfDay.plusDays(1).minusNanos(1);
            
            Long todayTotal = deliveryTaskMapper.countByDriverIdAndDateRange(driverId, startOfDay, endOfDay, tenantId);
            Long todayCompleted = deliveryTaskMapper.countByDriverIdStatusAndDateRange(driverId, 
                    DeliveryTask.Status.COMPLETED.getValue(), startOfDay, endOfDay, tenantId);
            Long todayInProgress = deliveryTaskMapper.countByDriverIdStatusAndDateRange(driverId, 
                    DeliveryTask.Status.IN_PROGRESS.getValue(), startOfDay, endOfDay, tenantId);
            
            statistics.put("todayTotal", todayTotal);
            statistics.put("todayCompleted", todayCompleted);
            statistics.put("todayInProgress", todayInProgress);
            statistics.put("todayPending", todayTotal - todayCompleted - todayInProgress);
            
        } catch (Exception e) {
            log.error("获取今日任务统计异常: driverId={}, tenantId={}", driverId, tenantId, e);
        }
        
        return statistics;
    }

    @Override
    public List<Map<String, Object>> exportTasks(String taskCode, Long driverId, Long orderId,
                                               Integer status, Integer priority, LocalDateTime startTime, LocalDateTime endTime, Long tenantId) {
        try {
            return deliveryTaskMapper.exportTasks(taskCode, driverId, orderId, status, priority, startTime, endTime, tenantId);
        } catch (Exception e) {
            log.error("导出任务信息异常: tenantId={}", tenantId, e);
            throw new RuntimeException("导出任务信息失败", e);
        }
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public Map<String, Object> importTasks(List<Map<String, Object>> taskList, Long tenantId) {
        Map<String, Object> result = new HashMap<>();
        int successCount = 0;
        int failCount = 0;
        StringBuilder errorMsg = new StringBuilder();
        
        try {
            for (int i = 0; i < taskList.size(); i++) {
                try {
                    Map<String, Object> taskData = taskList.get(i);
                    
                    DeliveryTask task = new DeliveryTask();
                    task.setOrderId(Long.valueOf(taskData.get("orderId").toString()));
                    task.setPickupAddress((String) taskData.get("pickupAddress"));
                    task.setDeliveryAddress((String) taskData.get("deliveryAddress"));
                    task.setReceiverName((String) taskData.get("receiverName"));
                    task.setReceiverPhone((String) taskData.get("receiverPhone"));
                    task.setPriority(Integer.valueOf(taskData.get("priority").toString()));
                    task.setTenantId(tenantId);
                    
                    if (createTask(task)) {
                        successCount++;
                    } else {
                        failCount++;
                        errorMsg.append("第").append(i + 1).append("行：创建失败；");
                    }
                    
                } catch (Exception e) {
                    failCount++;
                    errorMsg.append("第").append(i + 1).append("行：").append(e.getMessage()).append("；");
                }
            }
            
            result.put("success", true);
            result.put("successCount", successCount);
            result.put("failCount", failCount);
            result.put("errorMsg", errorMsg.toString());
            
            log.info("导入任务完成: 成功{}条，失败{}条，tenantId={}", successCount, failCount, tenantId);
            
        } catch (Exception e) {
            log.error("导入任务异常: tenantId={}", tenantId, e);
            result.put("success", false);
            result.put("message", "导入任务失败: " + e.getMessage());
        }
        
        return result;
    }

    @Override
    public Map<String, Object> optimizeTaskRoute(Long driverId, Long tenantId) {
        Map<String, Object> result = new HashMap<>();
        
        try {
            // 获取司机的待处理任务
            List<DeliveryTask> pendingTasks = getPendingTasksByDriverId(driverId, tenantId);
            
            if (pendingTasks.isEmpty()) {
                result.put("success", false);
                result.put("message", "暂无待处理任务");
                return result;
            }
            
            // 路径优化算法（这里简化处理，实际应该使用专业的路径规划算法）
            List<Map<String, Object>> optimizedRoute = new ArrayList<>();
            for (DeliveryTask task : pendingTasks) {
                Map<String, Object> routePoint = new HashMap<>();
                routePoint.put("taskId", task.getId());
                routePoint.put("taskCode", task.getTaskCode());
                routePoint.put("address", task.getDeliveryAddress());
                routePoint.put("longitude", task.getDeliveryLongitude());
                routePoint.put("latitude", task.getDeliveryLatitude());
                routePoint.put("priority", task.getPriority());
                optimizedRoute.add(routePoint);
            }
            
            // 按优先级排序（简化的优化策略）
            optimizedRoute.sort((a, b) -> {
                Integer priorityA = (Integer) a.get("priority");
                Integer priorityB = (Integer) b.get("priority");
                return priorityB.compareTo(priorityA); // 高优先级在前
            });
            
            result.put("success", true);
            result.put("optimizedRoute", optimizedRoute);
            result.put("totalTasks", pendingTasks.size());
            result.put("message", "路径优化完成");
            
        } catch (Exception e) {
            log.error("任务路径优化异常: driverId={}, tenantId={}", driverId, tenantId, e);
            result.put("success", false);
            result.put("message", "路径优化失败: " + e.getMessage());
        }
        
        return result;
    }

    @Override
    public List<Map<String, Object>> getTaskTrajectory(Long taskId, Long tenantId) {
        try {
            return deliveryTaskMapper.selectTaskTrajectory(taskId, tenantId);
        } catch (Exception e) {
            log.error("获取任务执行轨迹异常: taskId={}, tenantId={}", taskId, tenantId, e);
            return List.of();
        }
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean handleTaskException(Long taskId, Integer exceptionType, String exceptionDesc, String handleSuggestion, Long tenantId) {
        try {
            DeliveryTask task = deliveryTaskMapper.selectById(taskId);
            if (task == null || !tenantId.equals(task.getTenantId())) {
                return false;
            }
            
            // 更新任务异常信息
            task.setExceptionType(exceptionType);
            task.setExceptionDesc(exceptionDesc);
            task.setHandleSuggestion(handleSuggestion);
            task.setStatus(DeliveryTask.Status.EXCEPTION.getValue());
            task.setUpdateTime(LocalDateTime.now());
            
            int result = deliveryTaskMapper.updateById(task);
            
            log.info("处理任务异常成功: taskId={}, exceptionType={}, tenantId={}", taskId, exceptionType, tenantId);
            
            return result > 0;
            
        } catch (Exception e) {
            log.error("处理任务异常失败: taskId={}, tenantId={}", taskId, tenantId, e);
            throw new RuntimeException("处理任务异常失败", e);
        }
    }

    @Override
    public List<DeliveryTask> getExceptionTasks(Long tenantId) {
        return deliveryTaskMapper.selectByStatus(DeliveryTask.Status.EXCEPTION.getValue(), tenantId);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean reassignTask(Long taskId, Long newDriverId, String reason, Long tenantId) {
        try {
            DeliveryTask task = deliveryTaskMapper.selectById(taskId);
            if (task == null || !tenantId.equals(task.getTenantId())) {
                return false;
            }
            
            // 更新任务分配
            task.setDriverId(newDriverId);
            task.setStatus(DeliveryTask.Status.ASSIGNED.getValue());
            task.setReassignReason(reason);
            task.setUpdateTime(LocalDateTime.now());
            
            int result = deliveryTaskMapper.updateById(task);
            
            log.info("任务重新派单成功: taskId={}, newDriverId={}, reason={}, tenantId={}", 
                    taskId, newDriverId, reason, tenantId);
            
            return result > 0;
            
        } catch (Exception e) {
            log.error("任务重新派单异常: taskId={}, newDriverId={}, tenantId={}", taskId, newDriverId, tenantId, e);
            throw new RuntimeException("任务重新派单失败", e);
        }
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean cancelTask(Long taskId, String cancelReason, Long tenantId) {
        try {
            DeliveryTask task = deliveryTaskMapper.selectById(taskId);
            if (task == null || !tenantId.equals(task.getTenantId())) {
                return false;
            }
            
            // 检查任务状态，已完成的任务不能取消
            if (DeliveryTask.Status.COMPLETED.getValue().equals(task.getStatus())) {
                throw new RuntimeException("已完成的任务不能取消");
            }
            
            task.setStatus(DeliveryTask.Status.CANCELLED.getValue());
            task.setCancelReason(cancelReason);
            task.setCancelTime(LocalDateTime.now());
            task.setUpdateTime(LocalDateTime.now());
            
            int result = deliveryTaskMapper.updateById(task);
            
            log.info("取消任务成功: taskId={}, cancelReason={}, tenantId={}", taskId, cancelReason, tenantId);
            
            return result > 0;
            
        } catch (Exception e) {
            log.error("取消任务异常: taskId={}, tenantId={}", taskId, tenantId, e);
            throw new RuntimeException("取消任务失败", e);
        }
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean restoreTask(Long taskId, Long tenantId) {
        try {
            DeliveryTask task = deliveryTaskMapper.selectById(taskId);
            if (task == null || !tenantId.equals(task.getTenantId())) {
                return false;
            }
            
            // 只有已取消的任务可以恢复
            if (!DeliveryTask.Status.CANCELLED.getValue().equals(task.getStatus())) {
                throw new RuntimeException("只有已取消的任务可以恢复");
            }
            
            task.setStatus(DeliveryTask.Status.PENDING.getValue());
            task.setCancelReason(null);
            task.setCancelTime(null);
            task.setUpdateTime(LocalDateTime.now());
            
            int result = deliveryTaskMapper.updateById(task);
            
            log.info("恢复任务成功: taskId={}, tenantId={}", taskId, tenantId);
            
            return result > 0;
            
        } catch (Exception e) {
            log.error("恢复任务异常: taskId={}, tenantId={}", taskId, tenantId, e);
            throw new RuntimeException("恢复任务失败", e);
        }
    }

    @Override
    public Map<String, Object> getCompletionRateStatistics(String startDate, String endDate, Long tenantId) {
        Map<String, Object> result = new HashMap<>();
        
        try {
            List<Map<String, Object>> completionStats = deliveryTaskMapper.selectCompletionRateStatistics(startDate, endDate, tenantId);
            
            result.put("completionStats", completionStats);
            
            // 计算总体完成率
            long totalTasks = completionStats.stream()
                    .mapToLong(stat -> Long.parseLong(stat.get("totalTasks").toString()))
                    .sum();
            
            long completedTasks = completionStats.stream()
                    .mapToLong(stat -> Long.parseLong(stat.get("completedTasks").toString()))
                    .sum();
            
            double overallCompletionRate = totalTasks > 0 ? (double) completedTasks / totalTasks * 100 : 0;
            
            result.put("totalTasks", totalTasks);
            result.put("completedTasks", completedTasks);
            result.put("overallCompletionRate", overallCompletionRate);
            
        } catch (Exception e) {
            log.error("获取任务完成率统计异常: startDate={}, endDate={}, tenantId={}", 
                     startDate, endDate, tenantId, e);
        }
        
        return result;
    }

    @Override
    public Map<String, Object> getDriverCompletionRateStatistics(Long driverId, String startDate, String endDate, Long tenantId) {
        Map<String, Object> result = new HashMap<>();
        
        try {
            List<Map<String, Object>> driverStats = deliveryTaskMapper.selectDriverCompletionRateStatistics(driverId, startDate, endDate, tenantId);
            
            result.put("driverStats", driverStats);
            
            // 计算司机总体完成率
            long totalTasks = driverStats.stream()
                    .mapToLong(stat -> Long.parseLong(stat.get("totalTasks").toString()))
                    .sum();
            
            long completedTasks = driverStats.stream()
                    .mapToLong(stat -> Long.parseLong(stat.get("completedTasks").toString()))
                    .sum();
            
            double overallCompletionRate = totalTasks > 0 ? (double) completedTasks / totalTasks * 100 : 0;
            
            result.put("totalTasks", totalTasks);
            result.put("completedTasks", completedTasks);
            result.put("overallCompletionRate", overallCompletionRate);
            
        } catch (Exception e) {
            log.error("获取司机任务完成率统计异常: driverId={}, startDate={}, endDate={}, tenantId={}", 
                     driverId, startDate, endDate, tenantId, e);
        }
        
        return result;
    }
}